<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>iframe API test</title>
</head>
<body>
<script>
    /**
     * Ported from https://github.com/jitsi/jitsi-meet-torture/blob/master/src/test/resources/files/iframeAPITest.html
     */
    const blacklist = [ '__proto__', 'constructor', 'prototype' ];
    const paramStr = document.location.hash;
    const params = {};
    const paramParts = paramStr?.substring(1).split('&') || [];

    paramParts.forEach(part => {
        const param = part.split('=');
        const key = param[0];

        if (!key || key.split('.').some(k => blacklist.includes(k))) {
            return;
        }

        let value;

        try {
            value = param[1];


            const decoded = decodeURIComponent(value).replace(/\\&/, '&')
                .replace(/[\u2018\u2019]/g, '\'')
                .replace(/[\u201C\u201D]/g, '"');

            value = decoded === 'undefined' || decoded === '' ? undefined : JSON.parse(decoded);

        } catch (e) {
            console.error(`Failed to parse URL parameter value: ${String(value)}`, e);

            return;
        }
        params[key] = value;
    });
    const json = {
        config: {},
        interfaceConfig: {}
    };

    function log(msg) {
        console.log(`${new Date().toISOString()} [MeetTestIFrame] ${msg}`);
    }

    for (const param of Object.keys(params)) {
        let base = json;
        const names = param.split('.');
        const last = names.pop() ?? '';

        for (const name of names) {
            base = base[name] = base[name] || {};
        }

        base[last] = params[param];
    }

    const { config, domain, interfaceConfig, jwt, password, room:roomName, userInfo: uInfoObj } = json;
    let tenant = json.tenant || '';

    let userInfo;
    if (uInfoObj) {
        if (uInfoObj.length > 0) {
            userInfo = JSON.parse(uInfoObj);
        } else if (Object.keys(uInfoObj).length) {
            userInfo = uInfoObj;
        }
    }

    if (tenant.length > 0) {
        tenant = tenant + '/';
    }

    const options = {
        jwt,
        roomName: `${tenant}${roomName}`,
        configOverwrite: config,
        interfaceConfigOverwrite: interfaceConfig,
        userInfo,
        onload: function () {
            log(`iframeAPI.onload`);

            // we use this to save data from api to be accessible to tests
            window.jitsiAPI.test = {};

            window.jitsiAPI.addEventListener('participantRoleChanged', function(event) {
                log(`participantRoleChanged: ${JSON.stringify(event)} myEndpointId:${window.jitsiAPI.test.myEndpointId}`);
                if (event.role === "moderator" && event.id === window.jitsiAPI.test.myEndpointId) {
                    window.jitsiAPI.test.isModerator = true;
                }
                window.jitsiAPI.test['participantRoleChanged'] = event;
            });
            window.jitsiAPI.addEventListener('audioAvailabilityChanged', function(event) {
                log(`audioAvailabilityChanged: ${JSON.stringify(event)}`);
                window.jitsiAPI.test.audioAvailabilityChanged = event;
            });
            window.jitsiAPI.addEventListener('videoAvailabilityChanged', function(event) {
                log(`videoAvailabilityChanged: ${JSON.stringify(event)}`);
                window.jitsiAPI.test.videoAvailabilityChanged = event;
            });
            window.jitsiAPI.addEventListener('videoConferenceJoined', function(event) {
                log(`videoConferenceJoined: ${JSON.stringify(event)}`);
                window.jitsiAPI.test.videoConferenceJoined = event;
                window.jitsiAPI.test.myEndpointId = event.id;
            });
            if (password && password.length > 0) {
                // join a protected channel with the password supplied
                window.jitsiAPI.on('passwordRequired', function ()
                {
                    window.jitsiAPI.executeCommand('password', password);
                });
            }
        }
    };

    const externalAPIScript = document.createElement('script');
    externalAPIScript.src = `https://${domain}/${tenant}external_api.js`;
    externalAPIScript.type = "text/javascript";
    externalAPIScript.onload = function(){
        log(`externalAPIScript.onload`);
        window.jitsiAPI = new JitsiMeetExternalAPI(domain, options);
    }
    document.getElementsByTagName('head')[0].appendChild(externalAPIScript);
</script>
</body>
</html>
